package com.auto.qinglong.net.client.beans

import com.auto.qinglong.utils.CronUnit
import com.auto.qinglong.utils.TimeUnit
import java.util.Locale

data class TaskResultBean(var data: List<TaskBean>? = null, var size: Int = 0)

data class TaskBean(
    var id: String = "",
    var name: String = "",
    var command: String = "",
    var schedule: String = "",
    var saved: String = "",
    var timestamp: String = "",
    var status: Float = 0f,
    var isSystem: Int = 0,
    var pid: String = "",
    var isDisabled: Int = 0,
    var isPinned: Int = 0,
    var log_path: String = "",
    var last_running_time: Long = 0,
    var last_execution_time: Long = 0,
    var createdAt: String = "",
    var updatedAt: String? = null
)

data class Task(
    var key: String = "",
    var name: String = "",
    var command: String = "",
    var state: String = "",
    var stateCode: Int = 0,
    var schedule: String = "",
    var lastExecuteTime: String = "",
    var lastRunningTime: String = "",
    var nextExecuteTime: String = "",
    var isPinned: Boolean = false
)

object TaskStateCode {
    const val STATE_RUNNING: Int = 0
    const val STATE_WAITING: Int = 1
    const val STATE_FREE: Int = 2
    const val STATE_LIMIT: Int = 3
    const val STATE_UNKOWN: Int = 4
}


fun TaskBean.toTask(): Task {
    val task = Task()
    task.key = id
    task.name = name
    task.isPinned = isPinned == 1
    task.command = command
    task.schedule = schedule
    //任务上次执行时间
    if (last_execution_time > 0) {
        task.lastExecuteTime = TimeUnit.formatDatetimeA(last_execution_time * 1000)
    } else {
        task.lastExecuteTime = "--"
    }

    //任务上次执行时长
    if (last_running_time >= 60) {
        task.lastRunningTime = String.format(
            Locale.CHINA,
            "%d分%d秒",
            last_running_time / 60,
            last_running_time % 60
        )
    } else if (last_running_time > 0) {
        task.lastRunningTime = String.format(Locale.CHINA, "%d秒", last_running_time)
    } else {
        task.lastRunningTime = "--"
    }

    //任务下次执行时间
    task.nextExecuteTime = CronUnit.nextExecutionTime(schedule, "--")

    // 任务状态
    if (status == 0f) {
        task.state = "运行中"
        task.stateCode = TaskStateCode.STATE_RUNNING
    } else if (isDisabled == 1) {
        task.state = "已禁止"
        task.stateCode = TaskStateCode.STATE_LIMIT
    } else if (status == 0.5f || status == 3f) {
        task.state = "队列中"
        task.stateCode = TaskStateCode.STATE_WAITING
    } else {
        task.state = "空闲中"
        task.stateCode = TaskStateCode.STATE_FREE
    }
    return task
}